<?php

/*
  https://github.com/atomicon/codeigniter-native-session
 *  */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Login extends CI_Controller {

    public function index() {
        //redireccion segura
        if ($this->session->userdata('access') == 'grant') {
            redirect(base_url() . 'panel');
        }
        $this->load->view('front_end/login_panel');
    }

    public function check() {

        // SET VALIDATION RULES
        $this->form_validation->set_rules('user_name', 'username', 'required|trim|xss_clean|min_length[4]|max_length[45]');
        $this->form_validation->set_rules('user_pass', 'password', 'required|trim|xss_clean|min_length[4]|max_length[45]');

        // has the form been submitted and with valid form info (not empty values)
        if (!($this->input->post('loginFormSubmit') && $this->form_validation->run())) {
            redirect('login');
        }
        //autenticacion segura
        $usuario = $this->security->xss_clean($this->input->post('user_name'));
        $pass = $this->security->xss_clean($this->input->post('user_pass'));
        $access = $this->autenticar($usuario, $pass);

        //acceso concedido
        if ($access == 'OK') {
            $this->session->set_userdata('access', 'grant');
            $responsable = $this->datosUsuario($usuario);
            $this->ciempies_model->registrar($this->input->ip_address(), date('Y-m-j H:i:s'), $this->input->post('user_name'));
            $this->session->set_userdata('responsableID', $responsable->IDRESPONSABLE);
            $this->session->set_userdata('responsableNombre', $responsable->NOMBRE);

            redirect('panel');
        } else {
            redirect('login');
        }
    }

    private function autenticar($usuario, $pass) {
        return $this->ciempies_model->autenticarUsuario($usuario, $pass)->ACCESS;
    }

    private function datosUsuario($user_name) {
        return $this->ciempies_model->datosResponsable($user_name);
    }

}
